<template>
    <div
        id="root" 
        :style="{height:height+'px'}"
        @touchstart="touchBegin"
        @touchmove="touchmove"
        @touchend="touchend"
    >
        <div id="content" :style="contentStyle" ref="content">
            <slot></slot>
        </div>
        <div 
            id="scroll-bar"
            :style="{height:barHeight+'px',top:barTop+'px',opacity:barOpacity}"
        ></div>
    </div>
</template>

<script>
export default {
    props:[
        "height",
        "width"
    ],
    data:function(){
        return {
            prevY:0,
            currentOffsetY:0,
            contentStyle:{
                transform:"translate(0,0)"
            },
            barHeight:0,
            barTop:0,
            barOpacity:0
        }
    },
    methods:{
        touchBegin(e){
            // console.log(e.touches[0])
            this.prevY = e.touches[0].pageY;
            this.contentStyle.transition = "";
        },
        touchmove(e){
            var currentY = e.touches[0].pageY;
            var offSet = currentY-this.prevY;
            
            if(this.currentOffsetY>0){
                offSet/=10;
            }
            var maxOffset = this.$refs.content.offsetHeight-this.height;
            maxOffset = - maxOffset;
            if(this.currentOffsetY<maxOffset){
                offSet/=10;
            }

            this.currentOffsetY+=offSet;
            this.contentStyle.transform="translate(0,"+this.currentOffsetY+"px)";
            this.prevY = currentY;
            //计算滚动条位置
            var ratio = this.currentOffsetY/maxOffset;
            this.barTop = (this.height-this.barHeight)*ratio;
            this.barOpacity = 1;
            //发射滚动事件
            this.$emit("didScroll",this.currentOffsetY);
        },
        touchend(e){
            if(this.currentOffsetY>0){
                this.currentOffsetY=0;
            }

            var maxOffset = this.$refs.content.offsetHeight-this.height;
            maxOffset = - maxOffset;
            if(this.currentOffsetY<maxOffset){
                this.currentOffsetY=maxOffset
            }

            this.contentStyle.transition = "all 0.3s";

            this.contentStyle.transform="translate(0,"+this.currentOffsetY+"px)";

            this.barOpacity = 0;
        }
    },
    mounted:function(){
        var ratio = this.height/this.$refs.content.offsetHeight;
        this.barHeight = this.height*ratio;
    },
    

}
</script>

<style scoped>
    #root{
        overflow: hidden;
        position: relative;
    }

    #content{
        display: inline-block;
        width: 100%;
    }

    p{
        /*margin: 0;*/
    }

    #scroll-bar{
        position: absolute;
        right: 0;
        top: 0;
        width: 8px;
        background-color: rgba(0, 0, 0, 0.5);
        transition: opacity 0.3s;
    }

</style>